package com.learn.core.controller.manager;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.learn.common.annotation.Log;
import com.learn.common.annotation.UserLoginToken;
import com.learn.common.enums.BusinessType;
import com.learn.common.enums.OperatorType;
import com.learn.common.enums.ResultEnum;
import com.learn.common.utils.*;
import com.learn.common.utils.result.CommonResult;
import com.learn.core.domain.LOrganization;
import com.learn.core.dto.LOrganizationDTO;
import com.learn.core.service.ILOrganizationService;
import com.learn.framework.web.controller.WebController;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * @auther CodeGenerator
 * @create 2021-03-11 23:46:37
 * @describe 组织机构表前端控制器
 */
@Api("组织机构")
@RestController
@RequestMapping("/manager/org")
public class LOrganizationController extends WebController<LOrganization> {

	@Autowired
	private ILOrganizationService iLOrganizationService;

	//机构树
	@ApiOperation(value = "机构树")
	@UserLoginToken
	@PostMapping("/tree")
	public CommonResult<Object> tree(){
		try {
			QueryWrapper<LOrganization> queryWrapper = new QueryWrapper<LOrganization>();
			queryWrapper.eq("organization_type","1");
			List<LOrganization> lOrganizations = iLOrganizationService.queryLOrganizationAll(queryWrapper);
			if(lOrganizations.size()>0)
				return (CommonResult)ResultUtil.success(ResultEnum.SUCCESS,lOrganizations);
		}catch (Exception e){
			e.printStackTrace();
			return (CommonResult) ResultUtil.error(ResultEnum.ERROR);
		}
		return (CommonResult) ResultUtil.error(ResultEnum.ERROR);
	}

	//机构下拉
	@ApiOperation(value = "机构下拉")
	@UserLoginToken
	@PostMapping("/dropDown")
	public CommonResult<Object> dropDown(){
		try {
			List<LOrganization> lOrganizations = iLOrganizationService.list();
			if(lOrganizations.size()>0)
				return (CommonResult)ResultUtil.success(ResultEnum.SUCCESS,lOrganizations);
		}catch (Exception e){
			e.printStackTrace();
			return (CommonResult) ResultUtil.error(ResultEnum.ERROR);
		}
		return (CommonResult) ResultUtil.error(ResultEnum.ERROR);
	}

	//列表
	@ApiOperation(value = "获取列表")
	@UserLoginToken
	@PostMapping("/list")
	public PageResult<LOrganization> list(@RequestBody LOrganizationDTO lOrganizationDTO){
		try {
			if (lOrganizationDTO==null||lOrganizationDTO.getPage()==null||lOrganizationDTO.getRows()==null){
				return new PageResult<>(null, null, ResultEnum.ERROR);
			}
			PageHelper.startPage(lOrganizationDTO.getPage(),lOrganizationDTO.getRows());
			QueryWrapper<LOrganization> queryWrapper = new QueryWrapper<LOrganization>();
			if(lOrganizationDTO.getOrganizationId()!=null)
				queryWrapper.eq("parent_node",lOrganizationDTO.getOrganizationId());
			else {
				return new PageResult(null,null,ResultEnum.NOT_TEACHER_ORG);
			}
			if(lOrganizationDTO.getOrganizationCode()!=null)
				queryWrapper.like("organization_code",lOrganizationDTO.getOrganizationCode());
			if(lOrganizationDTO.getOrganizationName()!=null)
				queryWrapper.like("organization_name",lOrganizationDTO.getOrganizationName());
			if(lOrganizationDTO.getOrganizationType()!=null)
				queryWrapper.eq("organization_type",lOrganizationDTO.getOrganizationType());
			Page<LOrganization> lOrganizations = (Page<LOrganization>) iLOrganizationService.list(queryWrapper);
			if (CollectionUtils.isEmpty(lOrganizations)) {
				return new PageResult<>(null, null, ResultEnum.NOT_EEIST);
			}
			// 返回
			return new PageResult(lOrganizations.getTotal(), lOrganizations, ResultEnum.SUCCESS);
		}catch (Exception e){
			e.printStackTrace();
			return new PageResult(null,null,ResultEnum.ERROR);
		}
	}


	//新增
	@ApiOperation(value = "添加")
	@PostMapping("/add")
	@UserLoginToken
	@Log(title = "添加组织机构", businessType = BusinessType.INSERT, operatorType = OperatorType.SYSTEM)
	public CommonResult<Object> add(@RequestBody LOrganization lOrganization, HttpServletRequest request){
		String  token = request.getHeader("token");
		String userId = JwtUtil.getUserId(token);
		try {
			if(lOrganization!=null) {
				if (StringUtils.isEmpty(lOrganization.getOrganizationName())) {
					return (CommonResult) ResultUtil.error(ResultEnum.NOT_ORG_NAME);
				}
				if (StringUtils.isEmpty(lOrganization.getOrganizationType())) {
					return (CommonResult) ResultUtil.error(ResultEnum.NOT_ORG_TYPE);
				}
				if (StringUtils.isEmpty(lOrganization.getParentNode())) {
					lOrganization.setParentNode(0);
				}

				String organizationCode = CnToSpell.getPinYinHeadChar(lOrganization.getOrganizationName());
				lOrganization.setCreateTime(new Date());
				lOrganization.setCreateUser(userId);
				lOrganization.setOrganizationCode(organizationCode);
				if (iLOrganizationService.save(lOrganization)) {
					return (CommonResult) ResultUtil.success(ResultEnum.SUCCESS);
				}
			}
		}catch (Exception e){
			return (CommonResult)ResultUtil.error(ResultEnum.ERROR);
		}
		return  (CommonResult)ResultUtil.error(ResultEnum.ERROR);
	}


	//删除
	@ApiOperation(value = "删除")
	@PostMapping("/del")
	@UserLoginToken
	@Log(title = "删除组织机构", businessType = BusinessType.DELETE, operatorType = OperatorType.SYSTEM)
	public CommonResult<Object> del(@RequestBody LOrganization lOrganization){
		try {
			if(lOrganization!=null){
				if(lOrganization.getOrganizationId()!=null){
					List<Integer> ids = new ArrayList<>();
					ids.add(lOrganization.getOrganizationId());
					if(nodeStr(ids)){
						return (CommonResult)ResultUtil.success(ResultEnum.SUCCESS);
					}
				}
			}
		}catch (Exception e)
		{
			return (CommonResult)ResultUtil.error(ResultEnum.ERROR);
		}
		return (CommonResult)ResultUtil.error(ResultEnum.ERROR);
	}

	private Boolean nodeStr (List<Integer> lists) throws Exception{
		List<Integer> ids = new ArrayList<>();
		QueryWrapper<LOrganization> queryWrapper = new QueryWrapper<LOrganization>();
		for (int i = 0; i <lists.size() ; i++) {
			int orgid = lists.get(i);

			queryWrapper.eq("parent_node",orgid);
			List<LOrganization> lOrganizations = iLOrganizationService.list(queryWrapper);
			for (int j = 0; j < lOrganizations.size(); j++) {
				LOrganization lOrganization = lOrganizations.get(j);
				ids.add(lOrganization.getOrganizationId());
			}
		}
		if(ids.size() > 0){
			this.nodeStr(ids);
		}

		ids.addAll(lists);
		queryWrapper = new QueryWrapper<LOrganization>();
		queryWrapper.in(true, "organization_id", ids);
		iLOrganizationService.remove(queryWrapper);

		return Boolean.TRUE;
	}

	//更新
	@ApiOperation(value = "更新")
	@PostMapping("/edit")
	@UserLoginToken
	@Log(title = "更新组织机构", businessType = BusinessType.UPDATE, operatorType = OperatorType.SYSTEM)
	public CommonResult<Object> edit(@RequestBody LOrganization lOrganization, HttpServletRequest request) {
		String  token = request.getHeader("token");
		String userId = JwtUtil.getUserId(token);
		if(lOrganization!=null){
			lOrganization.setUpdateTime(new Date());
			lOrganization.setUpdateUser(userId);
			if(iLOrganizationService.updateById(lOrganization)){
				return (CommonResult)ResultUtil.success(ResultEnum.SUCCESS);
			}
		}
		return (CommonResult)ResultUtil.error(ResultEnum.ERROR);
	}

}

